package com.example.demo.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.SocketTimeoutException;
import java.util.Properties;

public class HttpUtil {
    /**
     * @param url
     * @param
     * @return
     */
//    Properties prop = System.getProperties();
//    // HTTP代理的IP设置
//        prop.setProperty("http.proxyHost", "172.16.8.67");
//    // HTTP代理的端口设置
//        prop.setProperty("http.proxyPort", "3128");
//    //这里也可以设置不需要使用代理的地址
//        prop.setProperty("http.nonProxyHosts", "localhost|172.16.*.*");
//    //设置HTTPS安全访问的代理服务器地址与端口
//        prop.setProperty("https.proxyHost", "172.16.8.67");
//        prop.setProperty("https.proxyPort", "3128");
    public static JSONObject sendGet(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        System.out.println(url);
        HttpGet method = new HttpGet(url);

       // HttpHost proxy = new HttpHost("172.16.8.67", 3128);
        // 依次是代理地址，代理端口号，协议类型
        RequestConfig requestConfig = RequestConfig.custom()
            //    .setProxy(proxy)
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(3000)
                .build();
          method.setConfig(requestConfig);
        try {
            CloseableHttpResponse result = httpclient.execute(method);
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    str = EntityUtils.toString(result.getEntity());
                    System.out.println(str);
                    jsonResult = (JSONObject) JSONObject.parse(str);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("get请求提交失败:" + url);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("get请求提交失败:" + url);
        }
        return jsonResult;
    }

    public static String sendPost(String url, String json) {
      //  HttpHost proxy = new HttpHost("172.16.8.67", 3128);
        //把代理设置到请求配置
     //   RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();
        //实例化CloseableHttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
      //  CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 设置请求超时
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000)						// 设置连接超时时间,单位毫秒。
                    .setConnectionRequestTimeout(1000)  			// 从连接池获取到连接的超时,单位毫秒。
                    .setSocketTimeout(1000).build();    	// 请求获取数据的超时时间,单位毫秒; 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
            httpPost.setConfig(requestConfig);

            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof SocketTimeoutException) {
                System.out.println("响应超时！！！");
            }
        } finally {
            // 释放资源
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        return resultString;

    }


    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static void main(String args[]) throws IOException {

        StringBuffer sb = new StringBuffer();
        sb.append("{" +
                "\"reqType\":0," +
                "    \"perception\": {" +
                "        \"inputText\": {" +
                "            \"text\": \"公交车\"" +
                "        }," +
                "        \"inputImage\": {" +
                "            \"url\": \"imageUrl\"" +
                "        }," +
                "        \"selfInfo\": {" +
                "            \"location\": {" +
                "                \"city\": \"河北\"," +
                "                \"province\": \"\"," +
                "                \"street\": \"\"" +
                "            }" +
                "        }" +
                "    }," +
                "    \"userInfo\": {" +
                "        \"apiKey\": \"9e12f5a1893b4ed09602abbb93a205f9\"," +
                "        \"userId\": \"123\"" +
                "    }" +
                "}");
      String result=  sendPost("http://openapi.tuling123.com/openapi/api/v2",sb.toString());
      System.out.println(result);
    }
}
